<?php

namespace App\Http\Controllers\Teacher;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Material;
use App\Http\Requests\MaterialRequest; //引入验证文件/app/Http/Requests/MaterialRequest.php
use App\Model\Subjects;
use App\Model\Grades;
use App\Model\Questions;
use Auth;

class MaterialController extends CommonController
{
    // 获取材料
    public function getMaterial(Material $material){
    	$data['materialCount'] = $material->where('user_id',Auth::id())->count();//获取总数目
        $data['materialAll'] = $material->where('user_id',Auth::id())->orderBy('id','desc')->with('getQuestion')->paginate(10);//所有列表
    	return view('teacher.material',$data);
    }

    public function add(MaterialRequest $request,Material $material,Subjects $subjects,Grades $grades){
    	$data['subjects'] = $subjects->all();
        $data['grades'] = $grades->all();
        if($request->isMethod('post')){
        	$info['title'] = $request->title;
	        $info['user_id'] = Auth::id();
	        $info['grade_id'] = $request->grade;
	        $info['subject_id'] = $request->subject;
	        $info['content'] = $request->content;
	        $info['add_time'] = time();
	        $material->insert($info);
	        return redirect('Teacher/material/list');
        }
    	return view('teacher.material_add',$data);
    }

    public function edit(MaterialRequest $request,Material $material,Subjects $subjects,Grades $grades,Questions $question,$id){
    	$data['subjects'] = $subjects->all();
        $data['grades'] = $grades->all();
        $data['info'] = $material->with('getQuestion')->find($id);
        if($request->isMethod('post')){
        	$info['title'] = $request->title;
        	$info['grade_id'] = $request->grade;
	        $info['subject_id'] = $request->subject;
	        if(!empty($request->content)){
	        	$info['content'] = $request->content;
	        }
	        $material->where('id',$id)->update($info);
        }
        return view('teacher.material_edit',$data);
    }

    public function del(Material $material,Questions $question,$id){
    	$material->where('id',$id)->delete();
    	$question->where('material',$id)->update(['material'=>0]);
    	return redirect('Teacher/material/list');
    }


    // 绑定题目
    public function binds(Request $request,Questions $question,$id){
    	$mid = $request->material;
    	$materialId = $id;
    	$question->where(['id'=>$mid,'author'=>Auth::id()])->update(['material'=>$materialId]);
    	return redirect("Teacher/material/edit/".$materialId);

    }

    // 删除题目
    public function del_question(Request $request,Questions $question){
    	$id = $request->id;
    	$question->where('id',$id)->update(['material'=>0]);
    	return 1;
    }
}
